package org.jeecg.modules.xl.as.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.annotation.Export2Swagger;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.xl.as.entity.XlCustomerAs;
import org.jeecg.modules.xl.as.service.IXlCustomerAsService;
import org.jeecg.modules.xl.common.XlLogUtil;
import org.jeecg.modules.xl.shengfutong.config.ShengftConf;
import org.jeecg.modules.xl.shengfutong.request.OrderRefundRequest;
import org.jeecg.modules.xl.shengfutong.response.RefundResponse;
import org.jeecg.modules.xl.shengfutong.util.ShengFuTongSignUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;

/**
* 退货退款售后单主表(xl_customer_as)表控制层
*
* @author xxxxx
*/
@RestController
@RequestMapping("/xlas/pc")
@Export2Swagger
public class XlCustomerAsController {

    @Resource
    private IXlCustomerAsService xlCustomerAsService;
    @ApiOperation(value = "获取售后单列表", notes = "获取售后单列表")
    @GetMapping(value = "/getASListByPage")
    public Result<IPage<XlCustomerAs>> getASListByPage(XlCustomerAs xlCustomerAs,
                                                       @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                       @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                       HttpServletRequest req) {
        QueryWrapper<XlCustomerAs> queryWrapper = QueryGenerator.initQueryWrapper(xlCustomerAs, req.getParameterMap());
        Page<XlCustomerAs> page = new Page<XlCustomerAs>(pageNo, pageSize);
        IPage<XlCustomerAs> pageList = xlCustomerAsService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @ApiOperation(value = "获取售后单列表", notes = "获取售后单列表")
    @PostMapping(value = "/audit")
    @Export2Swagger
    public Result<String> audit(@RequestBody XlCustomerAs dto ) throws Exception {
        XlCustomerAs entity = new XlCustomerAs();
        entity.setAsId(dto.getAsId());
        boolean isAgreen =false;
        if("同意".equals(dto.getAsStatus())){
            entity.setAsStatus("退款中");
            entity.setIsApproved("同意");
            isAgreen = true;
        }else{
            entity.setAsStatus(dto.getAsStatus());
            entity.setIsApproved("拒绝");
        }
        entity.setIsApproved(dto.getIsApproved());
        entity.setRejectReason(dto.getRejectReason());
        entity.setRefundAmount(dto.getRefundAmount());
        xlCustomerAsService.updateById(entity);
        //退款
        if(isAgreen){//同意调用退款接口

            XlCustomerAs tmp = xlCustomerAsService.getById(dto.getAsId());
            //OrderRefundRequest request = OrderRefundRequest.buildOrderRefund(tmp.getOrderCode(),tmp.getAsCode() ,Integer.valueOf(tmp.getProductTotalAmount().intValue()*100),tmp.getApplyReason());

            BigDecimal ss = BigDecimal.valueOf(tmp.getRefundAmount().doubleValue()*100);
            ss.setScale(0,BigDecimal.ROUND_HALF_UP);
            OrderRefundRequest request = OrderRefundRequest.buildOrderRefund(tmp.getOrderCode(),
                    tmp.getAsCode() ,ss.intValue(),tmp.getApplyReason());//退款1分钱

            String sign = ShengFuTongSignUtil.sign(BeanUtil.beanToMap(request), ShengftConf.PRIVATEKEY);// WalletSignUtils.sign(request, AggreConfig.PRIVATEKEY, SignType.RSA, new String[]{"sign"});
            request.setSign(sign);
            System.out.println("OrderRefundRequest request : "+ JSON.toJSONString(request));
            String resultJsonTemp = HttpUtil.post(ShengftConf.URL.concat("/refund/orderRefund"), JSON.toJSONString(request));

            System.out.println("OrderRefundRequest response : "+resultJsonTemp);

            RefundResponse response = JSONUtil.toBean(resultJsonTemp, RefundResponse.class);
            if("SUCCESS".equals(response.getResultCode())){
                //退款成功，直接更新为未退款成功
                XlCustomerAs xlCustomerAs = new XlCustomerAs();
                xlCustomerAs.setAsId(dto.getAsId());
                xlCustomerAs.setAsStatus("退款成功");
                new XlLogUtil().insertLog(entity.getAsCode(),"审核","售后单审核",new Date(),"待审核","退款成功");
            }else{
                new XlLogUtil().insertLog(entity.getAsCode(),"审核","售后单审核",new Date(),"待审核","退款中");
            }

            //boolean verify = WalletSignUtils.verify(response, AggreConfig.PUBLICKEY, response.getSign(), SignType.RSA, new String[]{"sign"});
            //System.out.println("验证签名结果："+verify);
        }else{
            new XlLogUtil().insertLog(entity.getAsCode(),"审核","售后单审核",new Date(),"待审核","拒绝");

        }

        return Result.OK("审核成功");
    }

}
